package com.logic.modular.game.shop;

import com.logic.modular.game.shop.domain.PlayerShop;
import com.logic.modular.game.player.info.service.PlayerServiceImpl;
import com.comment.pojo.domain.logic.core.CoreShopGoods;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 商品定时任务
 * @author cxy
 * @since 2024-11-06 10:32:23
 */
@Service
@Slf4j
public class ShopScheduledTask {
    @Resource
    private PlayerServiceImpl playerService;

    /**
     * 每日刷新
     */
    @Scheduled(cron = " 0 0 0 * * ?")
    public void listDayShop() {
        log.info("每日刷新");
        refreshByNum(1);
    }

    /**
     * 每周刷新
     */
    @Scheduled(cron = "0 0 0 1/7 * ?")
    public void listWeeklyShop() {
        log.info("每周刷新");
        refreshByNum(2);
    }

    /**
     * 每月一次
     */
    @Scheduled(cron = "0 0 0 1 * ?")  // 每月午夜刷新
    public void listSeasonalShop() {
        log.info("每月刷新");
        refreshByNum(3);
    }

    /**
     * 每6个小时执行一次
     */
    @Scheduled(cron = "0 0 0/6 * * ?")
    public void randomTimingEquip() {
        log.info("6小时刷新装备");
        // 获取所有主键
        Set<Long> playerIds = playerService.obtainPlayerIds();
        playerIds.forEach(playerId -> {
            PlayerShop playerShop = PlayerShop.get(playerId);
            if (playerShop==null) {
                return;
            }
            // 刷新
            playerShop.refreshEquip();
            // 保存
            playerShop.save();
        });
    }

    private void refreshByNum(int limitType) {
        Set<Long> playerIds = playerService.obtainPlayerIds();
        playerIds.forEach(playerId -> {
            PlayerShop playerShop = PlayerShop.get(playerId);
            // 刷新
            Map<String, CoreShopGoods> collect = playerShop.getGoodsMap().values().stream()
                    .filter(item -> item.getLimitType() == limitType)
                    .peek(item -> item.setBuyNum(0))
                    .collect(Collectors.toMap(item -> item.getId().toString(), item -> item));
            // 保存
            playerShop.setGoodsMap(collect);
            playerShop.save();
        });
    }
}

